package com.dikang.keer.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dikang.common.constant.ProductConstant;
import com.dikang.common.utils.PageUtils;
import com.dikang.common.utils.Query;
import com.dikang.keer.product.dao.AttrDao;
import com.dikang.keer.product.entity.AttrAttrgroupRelationEntity;
import com.dikang.keer.product.entity.AttrEntity;
import com.dikang.keer.product.entity.AttrGroupEntity;
import com.dikang.keer.product.service.AttrAttrgroupRelationService;
import com.dikang.keer.product.service.AttrGroupService;
import com.dikang.keer.product.service.AttrService;
import com.dikang.keer.product.service.CategoryService;
import com.dikang.keer.product.vo.AttrRespVo;
import com.dikang.keer.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationService attrgroupRelationService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVo attr) {
        // 添加Pms_attr

        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        attrEntity.setGroupId(attr.getAttrGroupId());
        baseMapper.insert(attrEntity);
        // 添加pms_attr_attrgroup_relation

        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
        if (attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
        }

        System.out.println(attrAttrgroupRelationEntity);
        attrgroupRelationService.save(attrAttrgroupRelationEntity);

    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long cateLogId, String attrType) {
        QueryWrapper<AttrEntity> attrWrapper = new QueryWrapper<>();
        attrWrapper.eq("attr_type","base".equalsIgnoreCase(attrType)? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() :ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            attrWrapper.and((obj) -> obj.eq("attr_id", key).or().like("attr_name", key));
        }
        if (cateLogId != 0) {
            attrWrapper.eq("catelog_id", cateLogId);
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrWrapper);
        PageUtils pageUtils = new PageUtils(page);
    List<AttrRespVo> respVos =
        page.getRecords().stream()
            .map(
                (item) -> {
                  AttrRespVo attrRespVo = new AttrRespVo();
                  BeanUtils.copyProperties(item, attrRespVo);
                  // 如果是属性才需要设立分组，sale是不会设立的
                  if ("base".equalsIgnoreCase(attrType)){
                      QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
                      if (attrRespVo.getAttrId() != null) {
                          wrapper.eq("attr_id", attrRespVo.getAttrId());
                          AttrAttrgroupRelationEntity one = attrgroupRelationService.getOne(wrapper);
                          if (one != null) {
                              AttrGroupEntity attrgroup = attrGroupService.getById(one.getAttrGroupId());
                              if (attrgroup != null) {
                                  attrRespVo.setGroupName(attrgroup.getAttrGroupName());
                              }
                          }
                      }
                  }

                  if (attrRespVo.getCatelogId() != null) {
                    attrRespVo.setCatelogName(
                        categoryService.getById(item.getCatelogId()).getName());
                  }
                  return attrRespVo;
                })
            .collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrRespVo(Long attrId) {

        AttrEntity attr = this.getById(attrId);
      if (attr !=null){
          AttrRespVo attrRespVo = new AttrRespVo();
          BeanUtils.copyProperties(attr,attrRespVo);
          attrRespVo.setCatelogPath(categoryService.getcatelogPath(attr.getCatelogId()));
        if (attrRespVo.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            QueryWrapper wrapper =new QueryWrapper<AttrAttrgroupRelationEntity>();
            wrapper.eq("attr_id",attrId);
            AttrAttrgroupRelationEntity attrgroupRelationEntity = attrgroupRelationService.getOne(wrapper);
            if (attrgroupRelationEntity!=null){
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupRelationEntity.getAttrGroupId());
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
          return attrRespVo;
      }
      return null;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        baseMapper.updateById(attrEntity);
        if (attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
            attrgroupRelationService.updateById(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils getNoattrRelation(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupId);
        //获取当前分类的id
        Long catelogId = attrGroupEntity.getCatelogId();

        //2、当前分组只能关联别的分组没有引用的属性
        //2.1）、当前分类下的其它分组
        List<AttrGroupEntity> groupEntities = attrGroupService.list(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));

        //获取到所有的attrGroupId
        List<Long> collect = groupEntities.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());


        //2.2）、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = attrgroupRelationService.list
                (new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));

        List<Long> attrIds = groupId.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3）、从当前分类的所有属性移除这些属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if (attrIds != null && attrIds.size() > 0) {
            queryWrapper.notIn("attr_id", attrIds);
        }

        //判断是否有参数进行模糊查询
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((w) -> {
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        PageUtils pageUtils = new PageUtils(page);


        return pageUtils;
    }

}